<?php

namespace backend\controllers;


use common\models\MoneyChange;
use common\models\Shop;
use common\models\Withdraw;
use common\service\CommonService;
use common\service\ConstantService;
use common\service\WechatService;

class WithdrawController extends BaseController
{
    /**
     * 列表
     * @return string
     */
    public function actionIndex(){
       if($this->isAjax() && $this->isGet()){
           //搜索条件  订单号 店铺名称 创建时间区间值
           $withdraw_model = Withdraw::find();
           if(!empty($this->get('withdraw_no'))){
               $withdraw_model->andWhere(['like','withdraw_no',$this->get('withdraw_no')]);
           }
           if(!empty($this->get('shop_name'))){
               $withdraw_model->andWhere(['like','shop_name',$this->get('shop_name')]);
           }
           if(!empty($this->get('start_time'))){
               $withdraw_model->andWhere(['>=','create_time',strtotime($this->get('start_time'))]);
           }
           if(!empty($this->get('end_time'))){
               $withdraw_model->andWhere(['=<','create_time',strtotime($this->get('end_time'))]);
           }

           $p = intval( $this->get('page',1) );
           $this->page_size = intval( $this->get('limit',10) );
           $p = ( $p > 0 )? $p : 1;
           $count = $withdraw_model->count();

           $offset = ($p - 1) * $this->page_size;

           $lists = $withdraw_model->orderBy(['id' => 'desc'])
               ->offset( $offset )
               ->limit( $this->page_size )
               ->asArray()
               ->all();

           return $this->renderPageJson($lists,$count,ConstantService::$response_tab_success);
       }
        return $this->render('index');

    }

    /**
     * 查看单个
     */
    public function actionInfo(){
        $id = $this->get('id');
        $row = Withdraw::find()->where(['id'=>$id])->asArray()->one();
        return $this->render('info',['row'=>$row]);
    }

    /**
     * 修改状态 通过和未通过
     */
    public function actionChangeStatus(){
        if($this->isPost() && $this->isAjax()){
            $id = $this->post('id');
            $status = $this->post('status');
            $dismissal = $this->post('dismissal','');
            if(empty($status) || empty($id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            if($status == ConstantService::$withdraw_status['FAIL'] && empty($dismissal)){
                return $this->renderJson([],'拒绝原因不允许为空',ConstantService::$response_fail);
            }
            $withdrow = Withdraw::findOne(['id'=>$id]);
            $withdrow->withdraw_status = $status;
            $withdrow->examine_time = time();
            $withdrow->dismissal = $dismissal;
            if($withdrow->save()){
                if($status == 1){
                    //拒绝需要将服务费加回去 shop表里面的
                    $shop = Shop::findOne(['id'=>$withdrow['shop_id']]);
                    $shop->service_money = sprintf("%.2f",$shop['service_money'] + $withdrow['shop_service_money']);
                    $shop->save();

                    $this->_changeMoney($withdrow['shop_id'],$withdrow['withdraw_money'],$withdrow['shop_service_money']);
                }
                return $this->renderJson([],'操作成功',ConstantService::$response_success);
            }
            return $this->renderJson([],'操作失败,请稍后再试',ConstantService::$response_fail);
        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);
    }


    /**
     * 确认提现
     */
    public function actionPayMoney(){
        if($this->isAjax() && $this->isPost()){
            $id = $this->post('id');
            if(empty($id)){
                return $this->renderJson([],'参数错误',ConstantService::$response_fail);
            }
            $withdraw = Withdraw::find()->where(['id'=>$id])->one();
            if($withdraw['withdraw_status'] != 2){
                return $this->renderJson([],'该申请不存在',ConstantService::$response_fail);
            }
            $mch_id = \Yii::$app->params['wechat']['mchid'];
            $wechat_key = \Yii::$app->params['wechat']['key'];
            $mch_appid = \Yii::$app->params['wechat']['appid'];
            //这个地方允许提现的金额应该要减掉服务费用
            $amount = sprintf("%.2f",$withdraw['withdraw_money'] - $withdraw['service_money']) * 100;
            $desc = '商家申请提现';
            if($withdraw['type'] == 0){
                //提现到微信
                $re = WechatService::pay_transfers($mch_appid,$mch_id,$withdraw['withdraw_no'],$withdraw['openid'],$amount,$desc,$wechat_key);
            }else{
                //提现到银行卡
                $re = WechatService::payBank($mch_id ,$withdraw['withdraw_no'],$withdraw['bank_no'], $withdraw['user_name'],$withdraw['bank_code'],$amount,$wechat_key,$desc);
            }
            if($re === false || $re['result_code'] == 'FAIL'){
                //提现失败 需要把钱反回到商户余额里面
                $withdraw->withdraw_status = ConstantService::$withdraw_status['CLOSE'];
                $withdraw->save();
                //失败需要将服务费加回去 shop表里面的
                $shop = Shop::findOne(['id'=>$withdraw['shop_id']]);
                $shop->service_money = sprintf("%.2f",$shop['service_money'] + $withdraw['shop_service_money']);
                $shop->save();

                $this->_changeMoney($withdraw['shop_id'],$withdraw['withdraw_money'],$withdraw['shop_service_money']);
                return $this->renderJson([],'提现失败',ConstantService::$response_fail);
            }
            //提现成功 修改状态
            $withdraw->withdraw_status = ConstantService::$withdraw_status['COMPLETED'];
            $withdraw->withdraw_serial = $re['payment_no'];
            $withdraw->complete_time = time();
            $withdraw->save();

            return $this->renderJson([],'操作成功',ConstantService::$response_success);


        }
        return $this->renderJson([],'参数错误',ConstantService::$response_fail);

    }

    /**
     * 添加金额记录变动
     * @param $shop_id
     * @param $current_money
     * @return bool
     */
    private function _changeMoney($shop_id,$current_money,$service_money){
        $shop = Shop::findOne(['id'=>$shop_id]);

        //商户余额
        $money = sprintf("%.2f",$shop['shop_money']) + sprintf("%.2f",$current_money)+ sprintf("%.2f",$service_money);

        $before_money = MoneyChange::find()
            ->where(['shop_id'=>$shop_id])
            ->orderBy(['id'=>SORT_DESC])
            ->one();
        $before_money = !empty($before_money) ? $before_money['after_money'] :'0.00';

        $change_model = new MoneyChange();
        $data['money'] = sprintf("%.2f",$current_money);
        $data['after_money'] = sprintf("%.2f",$money);
        $data['before_money'] = sprintf("%.2f",$before_money);
        $data['shop_id'] = $shop_id;
        $data['remark'] = '提现失败返回商户';
        $data['type'] = 0;
        $data['create_time'] = time();
        $change_model->setAttributes($data);
        $change_model->save();
        $shop->shop_money = sprintf("%.2f",$money);
        $shop->save();
        return true;
    }


}